package services

import (
	"GOPAAS/configs/config"
	"GOPAAS/internal/app/database"
	"GOPAAS/internal/app/global"
	"GOPAAS/internal/app/model"
	"GOPAAS/internal/utils"
	"GOPAAS/tools/sha"
	"database/sql"
	"errors"
	"fmt"
	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"gorm.io/gorm"
	"strconv"
	"time"
)

var db *gorm.DB

const BIND_MOBILE_TYPE_CACHE_KEY = "bind_mobile"
const LOGIN_MOBILE_TYPE_CACHE_KEY = "login_mobile"
const REGISTER_MOBILE_TYPE_CACHE_KEY = "register_mobile"
const PASS_MOBILE_TYPE_CACHE_KEY = "pass_mobile" //修改密码
const LOGIN_TOKEN_TYPE_CACHE_KEY = "login_token" //扫码登录

type UserService struct {
	model.ResUsers
}

func GetUserService(uid int64) *UserService {
	db = getDB()
	var user model.ResUsers
	if uid > 0 {
		db.First(&user, uid)
	}
	return &UserService{user}
}
func UserLoginByPass(userLogin string, pass string, registration_id string) (user_info SignRes, err error) {
	db = getDB()
	var user model.ResUsers
	res := db.Joins("join res_partner on res_users.partner_id=res_partner.Id").Where("(login = ? or login_mobile=? or email=?) and res_users.active=?", userLogin, userLogin, userLogin, true).Preload("Company").First(&user)
	if res.Error != nil {
		logrus.Error("查询失败:", res.Error)
		err = errors.New("用户或密码错误")
		return
	}
	if len(user.Password) > 0 {
		err = sha.SHA512Encrypt.Verify(pass, user.Password)
		if err != nil {
			logrus.Error("验证失败:", err)
			err = errors.New("用户或密码错误")
			return
		}
	}
	US := GetUserService(user.Id)
	access_token, token_err := US.SetToken(config.Conf.AppName)
	err = token_err
	if err != nil {
		logrus.Error(err)
		return
	}
	user_info, err = US.GetUserInfo()
	user_info.AccessToken = access_token
	user_info.DTcloudLoginUrl = US.GetIconJumpUrl(access_token)
	if registration_id != "" {
		//设置极光信息
		US.SetJiGuangInfo(registration_id)
	}

	return
}

// UserLoginOneStep 直接登录(不存在直接创建)
func UserLoginOneStep(userLogin string, registration_id string) (user_info SignRes, err error) {
	db = getDB()
	var user model.ResUsers
	db.Where("(login = ? or login_mobile=?) and active=?", userLogin, userLogin, true).Preload("Partner").Preload("Company").First(&user)
	if user.Id == 0 {
		//直接创建用户
		aUser, aErr := AddUser(db, "牛人", userLogin, config.Conf.DefaultPassword, "", userLogin, 1, 0)
		if aErr.Err != nil {
			return
		}
		user = aUser
	}
	US := GetUserService(user.Id)
	access_token, token_err := US.SetToken(config.Conf.AppName)
	err = token_err
	if err != nil {
		logrus.Error(err)
		return
	}
	user_info, err = US.GetUserInfo()
	user_info.AccessToken = access_token
	user_info.DTcloudLoginUrl = US.GetIconJumpUrl(access_token)
	if registration_id != "" {
		//设置极光信息
		US.SetJiGuangInfo(registration_id)
	}
	return
}

// UserLoginByToken 获取app扫码登录结果
func UserLoginByToken(token string) (user_info SignRes, err error) {
	db = getDB()
	cach_key := LOGIN_TOKEN_TYPE_CACHE_KEY + ":" + token
	// 获取值， 并断言
	c = GetCache()
	fmt.Println("----------------UserLoginByToken------------------")
	fmt.Println(cach_key)
	if x, left, found := c.GetWithExpiration(cach_key); found {
		user_id := x.(int64)
		fmt.Printf("当前用户为：%d", user_id)
		//user_id, _ := strconv.Atoi(user_id_str)
		if time.Now().After(left) {
			err = errors.New("二维码已经失效")
			return
		}
		if user_id > 0 {
			user_service := GetUserService(user_id)
			access_token, token_err := user_service.SetToken(config.Conf.AppName)
			err = token_err
			if err != nil {
				logrus.Error("验证失败:", err)
				return
			}
			user_info, err = user_service.GetUserInfo()
			user_info.AccessToken = access_token
			user_info.DTcloudLoginUrl = user_service.GetIconJumpUrl(access_token)
			c.Delete(cach_key)
			return
		}
	}
	err = errors.New("请先获取二维码")
	return
}

// AppCheckLogin app确认登录
func AppCheckLogin(key string, user_id int64) (err error) {
	c = GetCache()
	//确认登录
	key = LOGIN_TOKEN_TYPE_CACHE_KEY + ":" + key
	if _, left, found := c.GetWithExpiration(key); found {
		if time.Now().Before(left) {
			left_time := time.Since(left)
			c.Set(key, user_id, -left_time)
			return
		} else {
			err = errors.New("key 已经过期")
			return
		}
	}
	err = errors.New("key 不存在或已经过期")
	return
}

// GenerateUserLoginQrCode 生成登录二维码地址
func GenerateUserLoginQrCode(token string) string {
	c = GetCache()
	cach_key := LOGIN_TOKEN_TYPE_CACHE_KEY + ":" + token
	c.Set(cach_key, 0, 5*time.Minute)
	app_url := utils.Base64([]byte(`{"key":"` + token + `"}`))
	qr_url := "/web/qrcode?url=" + app_url
	return qr_url
}

// UserLoginByCode 手机验证码登陆
func UserLoginByCode(mobile string, code string, registration_id string) (user_info SignRes, err error) {
	db = getDB()
	var user model.ResUsers
	res := db.Where("login_mobile=? and active=?", mobile, true).Preload("Partner").Preload("Company").First(&user)
	if res.Error != nil {
		err = res.Error
		logrus.Error("查询失败:", res.Error)
		return
	}
	cach_key := LOGIN_MOBILE_TYPE_CACHE_KEY + ":" + strconv.Itoa(int(user.Id)) + mobile
	// 获取值， 并断言
	c = GetCache()
	fmt.Println("----------------LoginMobile------------------")
	fmt.Println(cach_key)
	if x, found := c.Get(cach_key); found {
		true_code := x.(string)
		fmt.Println("当前验证码为：", true_code)
		if true_code == code {
			c.Delete(cach_key)
			user_service := GetUserService(user.Id)
			access_token, token_err := user_service.SetToken(config.Conf.AppName)
			err = token_err
			if err != nil {
				err = errors.New("验证失败1")
				logrus.Error("验证失败:", err)
				return
			}
			user_info, err = user_service.GetUserInfo()
			user_info.AccessToken = access_token
			user_info.DTcloudLoginUrl = user_service.GetIconJumpUrl(access_token)
			if registration_id != "" {
				//设置极光信息
				user_service.SetJiGuangInfo(registration_id)
			}
			return
		}
	}
	err = errors.New("验证失败")
	return
}

// SendBindVerifyCode 发送绑定手机验证码
func (u *UserService) SendBindVerifyCode(mobile string, user_id int64) (err error) {
	var user model.ResUsers
	db = getDB()
	db.Where("login_mobile=?", mobile).First(&user)
	if user.Id > 0 {
		err = errors.New("手机号已经被绑定")
		return
	}
	err = u.sendVerifyCode(BIND_MOBILE_TYPE_CACHE_KEY, mobile, user_id)
	return
}

// SendRegisterVerifyCode 发送注册手机验证码
func (u *UserService) SendRegisterVerifyCode(mobile string) (err error) {
	var user model.ResUsers
	db = getDB()
	db.Where("login_mobile=?", mobile).First(&user)
	if user.Id > 0 {
		err = errors.New("手机号已经被绑定")
		return
	}
	err = u.sendVerifyCode(REGISTER_MOBILE_TYPE_CACHE_KEY, mobile, 0)
	return
}

// SendLoginVerifyCode 发送登录手机验证码
func (u *UserService) SendLoginVerifyCode(mobile string) (err error) {
	var user model.ResUsers
	db = getDB()
	db.Where("login_mobile=?", mobile).First(&user)
	if user.Id == 0 {
		err = errors.New("手机号不存在")
		return
	}
	err = u.sendVerifyCode(LOGIN_MOBILE_TYPE_CACHE_KEY, mobile, user.Id)
	return
}

// SendPassVerifyCode 发送修改手机验证码
func (u *UserService) SendPassVerifyCode(mobile string) (err error) {
	var user model.ResUsers
	db = getDB()
	db.Where("login_mobile=?", mobile).First(&user)
	if user.Id == 0 {
		err = errors.New("手机号不存在")
		return
	}
	err = u.sendVerifyCode(PASS_MOBILE_TYPE_CACHE_KEY, mobile, user.Id)
	return
}

func getDB() *gorm.DB {
	if db == nil {
		db = database.GetInstance("postgresql")
	}
	return db
}

// IsLogin 当前是否登录状态
func IsLogin(user_id int64, access_token string) bool {
	db = getDB()
	var user model.ResUsers
	db.First(&user, user_id)
	if user_id != 0 && user.CompanyId > 0 && access_token != "" {
		res, _ := CheckToken(user_id, user.CompanyId, access_token)
		if res {
			return true
		}
	}
	return false
}

// CheckToken 校验token是否有效
func CheckToken(user_id int64, company_id int64, access_token string) (res bool, err error) {
	db = getDB()
	var token model.DtcloudToken
	result := db.Where("name=? and user_id=? and company_id=? and access_token=?", config.Conf.AppName, user_id, company_id, access_token).First(&token)
	if result.Error != nil {
		return false, result.Error
	}
	if time.Now().Format("2006-01-02") > token.DateEnd {
		err = errors.New("授权已到期")
		logrus.Error("授权已到期")
		return
	}
	if token.TokenDate.After(time.Now()) {
		return true, nil
	}
	return
}

type SignRes struct {
	Uid                int64   `json:"uid"`
	AccessToken        string  `json:"access_token"`
	Name               string  `json:"name"`
	LoginMobile        string  `json:"login_mobile"`
	Lang               string  `json:"lang"`
	Tz                 string  `json:"tz"`
	ExpiresIn          int     `json:"expires_in"`
	Login              string  `json:"login"`
	CompanyId          int64   `json:"company_id"`
	CountryId          int64   `json:"country_id"`
	CompanyIds         []int64 `json:"company_ids"`
	CompanyIdName      string  `json:"company_id_name"`
	PartnerId          int64   `json:"partner_id"`
	CompanyIdsName     []Area  `json:"company_ids_name"`
	Image128           string  `json:"image_128"`
	NotificationType   string  `json:"notification_type"`
	Signature          string  `json:"signature"`
	Groups             []int64 `json:"groups"`
	RegistrationId     string  `json:"registration_id"` //极光
	DTcloudLoginUrl    string  `json:"dtcloud_login_url"`
	Icon               string  `json:"icon"`                 //图标
	ShowNavbar         bool    `json:"show_navbar"`          //是否显示导航
	IsSystem           bool    `json:"is_system"`            //是否系统管理员
	IsAdmin            bool    `json:"is_admin"`             //是否管理员
	UserContext        string  `json:"user_context"`         //用户上下文
	DB                 string  `json:"db"`                   //数据库
	ServerVersion      string  `json:"server_version"`       //系统版本
	SupportUrl         string  `json:"support_url"`          //购买地址
	PartnerDisplayName string  `json:"partner_display_name"` //伙伴名称
	CreateDate         string  `json:"create_date"`          //注册时间
}

// GetUserInfo 获取用户信息
func (u *UserService) GetUserInfo() (user_info SignRes, err error) {
	db = getDB()
	var user model.ResUsers
	res := db.Preload("Partner").Preload("Company").First(&user, u.Id)
	if res.Error != nil {
		err = res.Error
		logrus.Error("查询失败:", res.Error)
		return
	}
	var c_company []model.ResCompanyUsersRel
	var company_ids []int64
	var company_ids_name_arr []Area
	db.Where("user_id=?", user.Id).Preload("Company").Find(&c_company)
	for _, v := range c_company {
		company_ids = append(company_ids, v.Cid)
		company_ids_name_arr = append(company_ids_name_arr, Area{
			v.Cid, v.Company.Name,
		})
	}
	user_info.Uid = user.Id
	user_info.Login = user.Login
	user_info.LoginMobile = user.LoginMobile.String
	user_info.CompanyId = user.CompanyId
	user_info.PartnerId = user.PartnerId
	user_info.Name = user.Partner.Name
	user_info.Lang = user.Partner.Lang.String
	user_info.CountryId = user.Partner.CountryId.Int64
	user_info.Tz = user.Partner.Tz.String
	user_info.ExpiresIn = 24 * 3600
	user_info.CompanyIdName = user.Company.Name
	user_info.CompanyIds = company_ids
	user_info.CompanyIdsName = company_ids_name_arr
	user_info.Image128 = GetImage(128, "res.partner", user.PartnerId)
	user_info.NotificationType = user.NotificationType
	user_info.Signature = user.Signature
	user_info.Icon = GetIcon()
	user_info.ShowNavbar = true
	user_info.IsSystem = true
	user_info.IsAdmin = true
	user_info.UserContext = ""
	user_info.DB = config.Conf.Database["postgresql"].DbName
	user_info.ServerVersion = ""
	user_info.SupportUrl = ""
	user_info.PartnerDisplayName = ""
	user_info.CreateDate = u.CreateDate.Format("2006-01-2 15:04:05")
	var groups []int64
	db.Model(&model.ResGroupsUsersRel{}).Where("uid=?", user.Id).Pluck("gid", &groups)
	user_info.Groups = groups
	return
}

// SetToken 设置token
func (u *UserService) SetToken(token_type string) (access_token string, err error) {
	db = getDB()
	var token model.DtcloudToken
	db.Where("name=? and user_id=? and company_id=?", token_type, u.Id, u.CompanyId).First(&token)
	if token.Id == 0 {
		token, err = u.CreateToken(token_type)
		access_token = token.AccessToken
	} else {
		if time.Now().Format("2006-01-02") > token.DateEnd {
			err = errors.New("授权已到期")
			return
		}
		over_date := time.Now().AddDate(0, 0, 1)
		access_token = utils.GetAccessToken(u.Login, token.Appid, token.Secret)
		token.AccessToken = access_token
		token.TokenDate = over_date
		result := db.Save(&token)
		err = result.Error
	}
	return
}
func (u *UserService) CreateToken(token_type string) (token model.DtcloudToken, err error) {
	appid := utils.GetAppid()
	secret := fmt.Sprintf("%x", utils.GetUuid(32, 6))
	access_token := utils.GetAccessToken(u.Login, appid, secret)
	over_date := time.Now().AddDate(0, 0, 1)
	token = model.DtcloudToken{
		Name:        token_type,
		Appid:       appid,
		Secret:      secret,
		AccessToken: access_token,
		TokenDate:   over_date,
		UserId:      u.Id,
		DateStart:   time.Now().Format("2006-01-02"),
		DateEnd:     time.Now().AddDate(1, 0, 0).Format("2006-01-02"),
		CompanyId:   u.CompanyId,
		State:       "新建",
	}
	result := db.Create(&token)
	err = result.Error
	//var advanced []model.DtcloudAdvanced
	////tokenAdvanced 克隆模版权限
	//db.Model(&model.DtcloudToken{}).Joins("left join dtcloud_advanced on dtcloud_token.id=dtcloud_advanced.token_id").Where("is_template=true").Select("dtcloud_advanced.*").Find(&advanced)
	//if len(advanced) > 0 {
	//	for k, _ := range advanced {
	//		advanced[k].TokenId = token.Id
	//		advanced[k].Id = 0
	//	}
	//	db.Create(&advanced)
	//}
	return
}

// SetJiGuangInfo 设置极光信息
func (u *UserService) SetJiGuangInfo(registration_id string) {
	db = getDB()
	u.RegistrationId = utils.NullStringValue(registration_id)
	db.Select("RegistrationId").Save(&u.ResUsers)
}

// AddLoginRecord 添加登录记录
func (u *UserService) AddLoginRecord(name string, model_number string, ip string, login string, state string, browser string, errs string) {
	var login_record model.IrLogin
	db = getDB()
	var user sql.NullInt64
	user.Int64 = u.Id
	if u.Id == 0 {
		user.Valid = false
	} else {
		user.Valid = true
	}
	login_record = model.IrLogin{
		Name:        name,
		ModelNumber: model_number,
		Login:       login,
		Date:        time.Now(),
		IP:          ip,
		State:       state,
		Browser:     browser,
		UserId:      user,
		Error:       errs,
	}
	db.Create(&login_record)
}

// AddUserLog 添加登录日志
func (u *UserService) AddUserLog() {
	var user_log = model.ResUsersLog{
		ResCommon: model.ResCommon{
			WriteUid:  u.Id,
			CreateUid: u.Id,
		},
	}
	db.Create(&user_log)
}

func (u *UserService) sendVerifyCode(category string, mobile string, user_id int64) (err error) {
	c = GetCache()
	cach_key := category + ":" + strconv.Itoa(int(user_id)) + mobile
	code := utils.GetVerifyCode(6)
	if x, found := c.Get(cach_key); found {
		code = x.(string)
	}
	var user model.ResUsers
	if user_id > 0 {
		db.First(&user, user_id)
		if time.Now().Before(user.DynamicPasswordDatetime) {
			code = user.DynamicPassword
		}
	}
	sms := GetSmsService()
	err = sms.SendVerifyCode(category, mobile, code)
	if err != nil {
		return
	}
	if user.Id > 0 {
		user.DynamicPassword = code
		//有效期十分钟
		user.DynamicPasswordDatetime = time.Now().Add(time.Minute * 10)
		db.Select("DynamicPassword", "DynamicPasswordDatetime").Save(&user)
	}
	// 设置缓存值并带上过期时间
	c.Set(cach_key, code, 10*time.Minute)
	return
}

func (u *UserService) IsGroupUser(group_ids []int64) bool {
	user_info, _ := u.GetUserInfo()
	return IsGroupAdmin(group_ids, user_info.Groups)
}

type SignupErr struct {
	Err  error
	Code int
}

// Signup 注册
func Signup(login string, password string, name string, email string, mobile string, code string, registration_id string) (user_info SignRes, err SignupErr) {
	c = GetCache()
	cach_key := REGISTER_MOBILE_TYPE_CACHE_KEY + ":0" + mobile
	fmt.Println("----------------RegisterMobile------------------")
	fmt.Println(cach_key)
	err.Err = CheckVerifyCode(cach_key, code)
	db = getDB()
	tx := db.Begin()
	var company_id int64
	var company model.ResCompany
	company, err = AddCompany(tx, name)
	if err.Err != nil {
		// 遇到错误时回滚事务
		tx.Rollback()
		return
	}
	company_id = company.Id
	user, err := AddUser(tx, name, login, password, email, mobile, company_id, 2)
	if err.Err != nil {
		// 遇到错误时回滚事务
		tx.Rollback()
		return
	}
	// 否则，提交事务
	tx.Commit()
	user_service := GetUserService(user.Id)
	user_info, err.Err = user_service.GetUserInfo()
	access_token, _ := user_service.SetToken(config.Conf.AppName)
	user_info.AccessToken = access_token
	user_info.DTcloudLoginUrl = user_service.GetIconJumpUrl(access_token)
	if registration_id != "" {
		//设置极光信息
		user_service.SetJiGuangInfo(registration_id)
	}
	return
}

// CheckVerifyCode 验证吗校验
func CheckVerifyCode(cach_key string, code string) error {
	return nil
	if x, found := c.Get(cach_key); found {
		true_code := x.(string)
		fmt.Println("当前验证码为：", true_code)
		if code != true_code {
			return errors.New("验证码错误")
		}
	} else {
		return errors.New("验证码不存在或已过期")
	}
	return nil
}

// AddUser 添加新用户
func AddUser(tx *gorm.DB, name string, login string, password string, email string, mobile string, company_id int64, user_type int) (user model.ResUsers, err SignupErr) {
	if tx == nil {
		tx = getDB()
	}
	var partner model.ResPartner
	tx.Where("login = ?", login).First(&user)
	if user.Id > 0 {
		err.Err = errors.New("账号已存在")
		err.Code = 1012
		return
	}
	tx.Where("mobile = ?", mobile).First(&partner)
	if partner.Id > 0 {
		err.Err = errors.New("手机号已存在")
		err.Code = 1012
		return
	}
	if email != "" {
		tx.Where("email = ?", email).First(&partner)
		if partner.Id > 0 {
			err.Err = errors.New("电子邮件已存在")
			err.Code = 1012
			return
		}
	}
	partner = model.ResPartner{Name: name, Email: utils.NullStringValue(email), Mobile: utils.NullStringValue(mobile), DisplayName: name, CountryId: sql.NullInt64{48, true}}
	password, _ = sha.SHA512Encrypt.Hash(password) // 预先处理密码加密，然后存储在数据库
	user = model.ResUsers{Login: login, Password: password, LoginMobile: utils.NullStringValue(mobile)}
	var result *gorm.DB
	if company_id == 0 {
		company_id = 1 //默认1
		partner.IsCompany = false
	} else {
		partner.IsCompany = true
	}
	partner.CompanyId = company_id
	result = tx.Select("Name", "Active", "Email", "Mobile", "CompanyId", "IsCompany", "DisplayName", "Lang", "Tz", "CreateDate", "WriteDate", "CountryId").Create(&partner)
	if result.Error != nil {
		err.Err = result.Error
		return
	}
	user.CompanyId = company_id
	user.PartnerId = partner.Id
	user.LoginMobile = utils.NullStringValue(mobile)
	result = tx.Select("Login", "LoginMobile", "Password", "Share", "CompanyId", "PartnerId", "CreateDate", "WriteDate", "NotificationType").Create(&user)
	if result.Error != nil {
		err.Err = result.Error
		return
	}
	result = tx.Model(&partner).Updates(map[string]interface{}{"login_id": user.Id})
	if result.Error != nil {
		err.Err = result.Error
		return
	}
	//groupuser-门户
	var guser = []model.ResGroupsUsersRel{{10, user.Id}}
	if user_type == 1 {
		//公共10
		guser = []model.ResGroupsUsersRel{{11, user.Id}}
	} else if user_type == 2 {
		//内部用户
		guser = []model.ResGroupsUsersRel{{1, user.Id}, {6, user.Id}}
	}
	result = tx.Create(&guser)
	if result.Error != nil {
		err.Err = result.Error
		return
	}
	//companyuser
	var cuser = model.ResCompanyUsersRel{Cid: company_id, UserId: user.Id}
	result = tx.Create(&cuser)
	if result.Error != nil {
		err.Err = result.Error
		return
	}
	return
}

// UpdatePasswordByCode 忘记密码
func UpdatePasswordByCode(mobile string, code string, new_pass string) (err error) {
	db = getDB()
	var user model.ResUsers
	res := db.Where("login_mobile=?", mobile).First(&user)
	if res.Error != nil {
		err = errors.New("手机号不存在！")
		logrus.Error("查询失败:", res.Error)
		return
	}
	c = GetCache()
	cach_key := PASS_MOBILE_TYPE_CACHE_KEY + ":" + strconv.Itoa(int(user.Id)) + mobile
	fmt.Println("----------------forgetMobile------------------")
	fmt.Println(cach_key)
	if x, found := c.Get(cach_key); found {
		true_code := x.(string)
		fmt.Println("当前验证码为：", true_code)
		if code != true_code {
			err = errors.New("验证码错误")
			return
		}
	} else {
		err = errors.New("验证码不存在或已过期")
		return
	}
	password, _ := sha.SHA512Encrypt.Hash(new_pass) // 预先处理密码加密，然后存储在数据库
	user.Password = password
	res = db.Select("password").Save(&user)
	err = res.Error
	return
}

// BindLoginMobile 手机号绑定用户
func (u *UserService) BindLoginMobile(mobile string, code string) error {
	var user model.ResUsers
	db.Where("login_mobile=? and id <> ?", mobile, u.Id).First(&user)
	if user.Id > 0 {
		return errors.New("手机号已经被绑定")
	}
	cach_key := BIND_MOBILE_TYPE_CACHE_KEY + ":" + strconv.Itoa(int(u.Id)) + mobile
	// 获取值， 并断言
	c = GetCache()
	fmt.Println("----------------BindLoginMobile------------------")
	fmt.Println(cach_key)
	if x, found := c.Get(cach_key); found {
		true_code := x.(string)
		if true_code == code {
			var user model.ResUsers
			db = getDB()
			db.First(&user, u.Id)
			user.LoginMobile = utils.NullStringValue(mobile)
			db.Select("LoginMobile").Save(&user)
			var partner model.ResPartner
			db.First(&partner, user.PartnerId)
			partner.Mobile = utils.NullStringValue(mobile)
			db.Select("Mobile").Save(&partner)
			c.Delete(cach_key)
			return nil
		}
	}
	return errors.New("验证码不正确")
}

// GetUserBaseInfo 获取个人用户基础信息
func (u *UserService) GetUserBaseInfo() (result global.BaseUserInfo, err error) {
	db = getDB()
	var partner model.ResPartner
	res := db.First(&partner, u.PartnerId)
	if res.Error != nil {
		return result, res.Error
	}
	result.Name = partner.Name
	result.Title = partner.Title.Int64
	result.AliasName = partner.DisplayName
	//result.SFZ = partner.SFZ
	result.Sex = partner.Sex
	result.Weixin = partner.Weixin
	result.Email = partner.Email.String
	result.QQ = partner.QQ
	result.CountryId = partner.CountryId.Int64
	result.StateId = partner.StateId.Int64
	result.CityId = partner.CityId.Int64
	result.StateId = partner.StateId.Int64
	result.AreaId = partner.AreaId.Int64
	result.Street = partner.Street.String
	result.ContactAddress = partner.ContactAddressComplete
	result.BirthDay = utils.NullTimeValueFormat(partner.Date, "2006-01-02")
	result.Image128 = GetImage(128, "res.partner", u.PartnerId)
	return
}

// SaveUserBaseInfo 设置个人用户基本信息
func (u *UserService) SaveUserBaseInfo(base global.CreateBaseUserInfo) (err error) {
	db = getDB()
	var partner model.ResPartner
	res := db.First(&partner, u.PartnerId)
	if res.Error != nil {
		return res.Error
	}
	//partner.Name = base.Name
	if base.AliasName.Valid {
		partner.DisplayName = base.AliasName.String
	}
	if base.Title.Valid {
		partner.Title = utils.NullInt64Value(base.Title.Int64)
	}
	//partner.SFZ = base.SFZ
	if base.Sex.Valid {
		partner.Sex = base.Sex.String
	}
	if base.Weixin.Valid {
		partner.Weixin = base.Weixin.String
	}
	if base.ContactAddress.Valid {
		partner.ContactAddressComplete = base.ContactAddress.String
	}
	if base.Email.Valid {
		partner.Email = utils.NullStringValue(base.Email.String)
	}
	if base.QQ.Valid {
		partner.QQ = base.QQ.String
	}
	if base.BirthDay.Valid {
		partner.Date = utils.NullDateValue(base.BirthDay.String)
	}
	if base.CountryId.Valid {
		partner.CountryId = utils.NullInt64Value(base.CountryId.Int64)
	}
	if base.StateId.Valid {
		partner.StateId = utils.NullInt64Value(base.StateId.Int64)
	}
	if base.CityId.Valid {
		partner.CityId = utils.NullInt64Value(base.CityId.Int64)
	}
	if base.AreaId.Valid {
		partner.AreaId = utils.NullInt64Value(base.AreaId.Int64)
	}
	if base.Street.Valid {
		partner.Street = utils.NullStringValue(base.Street.String)
	}
	err = db.Updates(&partner).Error
	return
}

// UpdatePassword 更新密码
func (u *UserService) UpdatePassword(old_pass string, new_pass string) (err error) {
	db = getDB()
	if len(u.Password) > 0 {
		err = sha.SHA512Encrypt.Verify(old_pass, u.Password)
		if err != nil {
			err = errors.New("旧密码错误")
			logrus.Error("验证失败:", err)
			return
		}
	}
	password, _ := sha.SHA512Encrypt.Hash(new_pass) // 预先处理密码加密，然后存储在数据库
	u.Password = password
	err = db.Select("password").Save(&u.ResUsers).Error
	return
}

// GetIconJumpUrl 获取跳转地址
func (u *UserService) GetIconJumpUrl(access_token string) string {
	db = getDB()
	url := GetDTcloudConfig("web.base.url")
	return fmt.Sprintf("%s/sso/login?login=%s&db=%s&access_token=%s", url, u.Login, config.Conf.Database["postgresql"].DbName, access_token)
}

// GetIcon 获取图标取公司图标
func GetIcon() string {
	return GetSimpleImage("res.company", 1, "favicon")
}

// IsWebLogin 当前是否登录状态
func IsWebLogin(c *gin.Context) bool {
	session := sessions.Default(c)
	access_token := session.Get("access_token")
	user_id := session.Get("user_id")
	company_id := session.Get("company_id")
	if user_id != nil && company_id != nil && access_token != nil {
		res, _ := CheckToken(user_id.(int64), company_id.(int64), access_token.(string))
		if res {
			return true
		}
	}
	return false
}
